<?php

namespace App\Http\Controllers\ChatGroup\Merchant;

use App\Http\Controllers\BaseController;
use App\Models\ChatGroup\ChatGroupFAQModel;
use App\Models\ChatGroup\ChatGroupHistoryModel;
use App\Models\ChatGroup\ChatGroupUserModel;
use App\Service\BaseService;
use App\Service\ChatGroup\ChatGroupHistoryService;
use App\Http\Middleware\OpenShop\MerchantAppAuth;
use App\Service\ChatGroup\ChatGroupNotifyService;
use App\Service\ChatGroup\ChatGroupSessionService;
use App\Service\ChatGroup\ChatGroupStructService;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class CustomerServeController extends BaseController
{
    /**
     * 进入会话
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public function enterSession(Request $request): JsonResponse
    {
        $shopId  = $request->header('shopId');
        $groupId = $request->get('groupId');
        $userId  = getRmsUserId();

        $this->validate($request, [
            'groupId' => 'required|integer',
        ]);

        return $this->success((new ChatGroupSessionService())->enterSession($shopId, $groupId,
            ChatGroupSessionService::FROM_APP, $userId));
    }

    /**
     * 查询聊天记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getChatHistory(Request $request)
    {
        $shopId   = $request->header('shopId');
        $groupId  = $request->get('groupId');
        $topMsgId = $request->get('topMsgId');
        $limit    = $request->get('limit', 30);
        $userId   = getRmsUserId();

        $this->validate($request, [
            'groupId'  => 'required|integer|min:1',
            'topMsgId' => 'nullable|integer',
            'limit'    => 'nullable|integer',
        ]);

        $data = ChatGroupHistoryService::getChatHistory($shopId, $groupId, $topMsgId, $limit, $userId);

        return $this->success($data);
    }

    /**
     * 会话评价
     * @param Request $request
     * @param int $groupId
     * @return JsonResponse
     * @throws ValidationException
     */
    public function appraise(Request $request, int $groupId): JsonResponse
    {
        $this->validate($request, [
            'msgId' => 'required|int',
            'score' => 'required|int',
            'solve' => 'required|int',
        ]);

        $shopId = (int)$request->header('shopId');
        $msgId  = (int)$request->post('msgId');
        $score  = (int)$request->post('score');
        $solve  = (int)$request->post('solve');

        // 评价人
        $operatorId = MerchantAppAuth::$userId;

        ChatGroupSessionService::appraise($shopId, $msgId, $score, $solve, $groupId, $operatorId);

        return $this->success();
    }

    /**
     * 呼叫人工
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     * @throws Exception
     */
    public function callServe(Request $request): JsonResponse
    {
        $shopId  = (int)$request->header('shopId');
        $groupId = $request->get('groupId');
        $userId  = getRmsUserId();

        $this->validate($request, [
            'groupId' => 'required|integer|min:1',
        ]);

        // 呼叫人工
        ChatGroupSessionService::callServe($shopId, $groupId, true, $userId);

        return $this->success();
    }

    /**
     * 取消呼叫
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     */
    public function cancelCall(Request $request): JsonResponse
    {
        $shopId  = $request->header('shopId');
        $groupId = $request->get('groupId');

        $this->validate($request, [
            'groupId' => 'required|integer|min:1',
        ]);

        ChatGroupSessionService::cancelCall($shopId, $groupId);

        return $this->success();
    }

    /**
     * 发送常见问题
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws Exception
     */
    public function sendFaq(Request $request)
    {
        $this->validate($request, [
            'groupId' => 'required|integer',
        ]);

        $shopId  = (int)$request->header('shopId');
        $groupId = (int)$request->post('groupId');
        $userId  = getRmsUserId();

        ChatGroupSessionService::sendFaq($shopId, $groupId, $userId);

        return $this->success();
    }

    /**
     * 常见问题列表
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     */
    public function faqLists(Request $request)
    {
        $pid = $request->get('pid', 0);

        $this->validate($request, [
            'parentId' => 'nullable|integer',
        ]);

        $data = ChatGroupFAQModel::getByPid($pid);

        return $this->success(['lists' => $data]);
    }

    /**
     * 获得常见问题答案
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     */
    public function faqAnswer(Request $request): JsonResponse
    {
        $this->validate($request, [
            'indexNumber' => 'required|string'
        ]);

        $indexNumber = $request->get('indexNumber');

        return $this->success(ChatGroupSessionService::faqAnswer($indexNumber));
    }

    /**
     * 问题答案-增加有用、无用操作
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     */
    public function faqAnswerOperate(Request $request): JsonResponse
    {
        $this->validate(
            $request, [
                'id'          => 'integer',
                'type'        => 'required|integer|' . Rule::in(array_keys(ChatGroupFAQModel::TYPE_USE_TEXT_MAPPING)),
                'chatGroupId' => 'integer',
                'msgId'       => 'integer',
            ]
        );

        $shopId  = (int)$request->header('shopId');
        $id      = (int)$request->get('id', 0);             // 问题id
        $type    = (int)$request->get('type', 0);           // 1-有用 2-无用
        $groupId = (int)$request->get('chatGroupId', 0);    // 群聊id
        $msgId   = (int)$request->get('msgId', 0);          // 当前消息id 与问题id存在一个即可

        if (!$id && !$msgId) {
            return BaseService::throwErr('问题Id错误');
        }
        $userId = getRmsUserId();

        return $this->success(ChatGroupSessionService::faqAnswerOperate($id, $type, $shopId, $groupId, $msgId, $userId));
    }
}
